package com.xyh.transaction.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.xyh.transaction.exception.ImageOperationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CosImageUtil {

    private static final String secretId = "AKIDBHICyUKzUp38zgFl8GDzbzBdzDFRWN2W";
    private static final String secretKey = "NZvCYn8KMG1d7Umqx54uY4PXTGtTqJj0";
    private static final String region = "ap-shanghai";

    private static final String cosEndpoint = "https://img-1323317179.cos.ap-shanghai.myqcloud.com/";

    public static COSClient createCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        return new COSClient(cred, clientConfig);
    }

    public static String uploadImage(String bucketName, String fileName, String formatName, MultipartFile imageFile) {
        COSClient cosClient = createCOSClient();

        String key = fileName + "." + formatName;

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(imageFile.getSize());
        try (InputStream inputStream = imageFile.getInputStream()) {
            // 上传文件到腾讯云 COS
            cosClient.putObject(bucketName, key, inputStream, objectMetadata);

            // 构造访问 URL
            return cosEndpoint + key;
        } catch (Exception e) {
            log.error("Exception during file upload: {}", e.getMessage(), e);
            throw new ImageOperationException("图片上传失败，原因：" + e.getMessage(), e);
        }
    }

    public static void deleteBatchImage(String  bucketName, List<String> keys){
        COSClient cosClient = createCOSClient();

        for (String key : keys) {
            cosClient.deleteObject(bucketName,key);
        }
    }

    public static void uploadLocalImage(String bucketName, String key, String localImagePath) {
        COSClient cosClient = createCOSClient();
        File localFile = new File(localImagePath);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        System.out.println("Image uploaded. RequestId: " + putObjectResult.getRequestId());
    }

    public static String downloadImage(String bucketName, String key, String localDirectory) {
        COSClient cosClient = createCOSClient();
        String localFilePath = localDirectory + File.separator + key;
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, new File(localFilePath));
        System.out.println("Image downloaded to: " + localFilePath);
        return localFilePath;
    }

    public static List<String> listAllImages(String bucketName) {
        COSClient cosClient = createCOSClient();
        List<String> imageKeys = new ArrayList<>();

        ObjectListing objectListing = cosClient.listObjects(bucketName);
        List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();

        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
            imageKeys.add(cosObjectSummary.getKey());
        }

        return imageKeys;
    }

    public static void main(String[] args) throws IOException {
        // 使用工具类示例


        String bucketName = "img-1323317179";
        String key = "test4.jpg";
        String localImagePath = "C:\\xiaoyh\\images\\test4.jpg";
        String localDirectory = "C:\\xiaoyh\\images\\download\\";

        // 获取所有图片
//        listAllImages(bucketName).forEach(System.out::println);
        System.out.println(listAllImages(bucketName).size());

        // 上传图片
//        cosImageUtil.uploadImage(bucketName, key, localImagePath);

        // 下载图片
//        cosImageUtil.downloadImage(bucketName, key, localDirectory);

    }
}
